package com.example.app.futures;

/**
 * @author wangzhuangzhuang
 * @DESC:
 * @date 2022-02-11 13:55
 */

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * Futures是一个抽象概念，表示一个值，该值可能在某一点变得可用。
 * 一个Future要么获得计算完的结果要么获得计算失败后的异常
 * Java在java.util.concurrent包中附带了Future接口，它使用Executor异步执行。
 * */
@Slf4j
public class FutureExample {

	public static void main(String[] args) throws ExecutionException, InterruptedException {
		ExecutorService es = Executors.newCachedThreadPool();
		Runnable task01 = new Runnable(){
			@Override
			public void run(){
				// do sth
				log.info("I am task01 ...");
			}
		};

		Callable<Integer> task02 = new Callable<Integer>(){
			@Override
			public Integer call() throws Exception{
				// do sth
				return new Integer(100);
			}
		};
		Future<?> f1 = es.submit(task01);
		Future<Integer> f2 = es.submit(task02);

		log.info("task01 is completed? " + f1.isDone());
		log.info("task02 is completed? " + f2.isDone());

		// waiting task01 completed
		while(f1.isDone()){
			log.info("task01 completed!");
			break;
		}

		// waiting task02 completed
		while(f2.isDone()){
			log.info("return value by task02: " + f2.get());
			break;
		}
	}
}